package cn.frank.framework.caesar.module.ai.openAi.util;

import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySourcesPropertyResolver;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

@Slf4j
public class OpenAiWebUtil {

    public static void main(String[] args) {
        System.out.println("Hello World: " + "cn.frank.framework.caesar caesar-module-ai-openAi 1.0.0 OpenAi");
    }

    static final boolean printSystemInfo = false;
    static final boolean printAppInfo = true;

    private static boolean isKeyMatched(String key) {
        return key.startsWith("server.ssl.")
                || key.startsWith("xxl.")
                || key.startsWith("spring.redis.")
                || key.startsWith("spring.datasource.")
                || key.startsWith("restful.viid.");
    }

    @SneakyThrows
    public static void printConfigInfo(ConfigurableApplicationContext context,String env) {
        String value = context.getEnvironment().getProperty(env);
        if(StrUtil.isNotBlank(value)){
            log.info("  |-- env:{}",value);
        }
    }

    @SneakyThrows
    public static void printConfigInfo(ConfigurableApplicationContext context) {
        // 获取应用程序名称、IP地址、端口和协议
        String name = context.getEnvironment().getProperty("spring.application.name");
        List<String> ipv4s = getIPv4List();
        String port = StrUtil.isBlank(context.getEnvironment().getProperty("server.port")) ? "8080" : context.getEnvironment().getProperty("server.port");
        String http = context.getEnvironment().getProperty("server.ssl.key-store") != null ? "https" : "http";

        StringBuilder message = new StringBuilder();
        List<Object> parms = new ArrayList<>();

        // 构建访问URL信息
        message.append("\n\tApplication '{}' is running! Access URLs:");
        parms.add(name);
        for (String ip : ipv4s) {
            message.append("\n\tDoc:       {}://{}:{}/doc.html");
            parms.add(http);
            parms.add(ip);
            parms.add(port);
        }

        // 添加配置详情信息
        message.append("\n----------------------------------------------------------");
        message.append("\n\tConfiguration Detail:");
        message.append("\n\tspring.profiles.active={}");
        parms.add(context.getEnvironment().getProperty("spring.profiles.active"));

        // 创建 PropertySourcesPropertyResolver 实例
        PropertySourcesPropertyResolver resolver = new PropertySourcesPropertyResolver(context.getEnvironment().getPropertySources());

        // 打印以特定前缀开头的配置项
        ConfigurableEnvironment env = context.getEnvironment();

        StringBuilder configMessage = new StringBuilder();
        boolean[] appConfigAdded = new boolean[]{false};
        boolean[] systemConfigAdded = new boolean[]{false};

        env.getPropertySources().forEach(propertySource -> {
            if (propertySource instanceof PropertiesPropertySource && printSystemInfo) {
                Map<String, Object> source = ((PropertiesPropertySource) propertySource).getSource();
                if (!source.isEmpty()) {
                    source.forEach((key, value) -> {
                        String resolvedValue = resolver.resolvePlaceholders(value.toString());
                        if (!systemConfigAdded[0]) {
                            configMessage.append("\n\t").append("系统配置：");
                            systemConfigAdded[0] = true;
                        }
                        configMessage.append("\n\t\tL配置 ").append(key).append(" = ").append(resolvedValue);
                    });
                }
            }
            if (propertySource instanceof MapPropertySource && printAppInfo) {
                Map<String, Object> source = ((MapPropertySource) propertySource).getSource();
                if (!source.isEmpty()) {
                    source.forEach((key, value) -> {
                        String resolvedValue = resolver.resolvePlaceholders(value.toString());
                        if (isKeyMatched(key)) {
                            if (!appConfigAdded[0]) {
                                configMessage.append("\n\t").append("程序配置：");
                                appConfigAdded[0] = true;
                            }
                            configMessage.append("\n\t\tL配置 ").append(key).append(" = ").append(resolvedValue);
                        }
                    });
                }
            }
        });

        // 将配置信息添加到主消息中
        if (configMessage.length() > 0) {
            message.append(configMessage);
        }

        message.append("\n----------------------------------------------------------");

        // 使用 String.format 来格式化消息
        log.info(message.toString(), parms.toArray());
    }

    private static List<String> getIPv4List() throws SocketException {
        List<String> ipv4List = new ArrayList<>();
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets)) {
            if (netint.isUp() && !netint.isVirtual() && !netint.isLoopback()) {
                for (InetAddress inetAddress : Collections.list(netint.getInetAddresses())) {
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        ipv4List.add(inetAddress.getHostAddress());
                    }
                }
            }
        }
        return ipv4List;
    }

}